﻿function Post(p) {
    var self = this;
    this.parent = p;
    this.editor = ko.observable();
    this.body = ko.observable();
    this.id = ko.observable();
    this.title = ko.observable().extend({ required: "Please enter title" });
    this.time = ko.observable();
    this.type = ko.observable();
    this.published = ko.computed(function () {
        return this.type() == 1;
    }, this);

    this.typeText = ko.computed(function () {
        return this.type() == 0 ? "Draft" : (this.type() == 1 ? "Published" : "Scheduled");
    }, this);

    this.categories = ko.observableArray();
    this.selectedCategories = ko.observableArray();
    this.selectedCategoriesJson = ko.computed(function () {
        var jsonArray = new Array();
        for (var idx = 0; idx < this.selectedCategories().length; idx++)
            jsonArray.push("{ \"CatID\": \"" + this.selectedCategories()[idx] + "\" }");
        return "[" + jsonArray.join() + "]";
    }, this);


    this.successMessage = ko.observable();
    this.errors = ko.observableArray();
    this.errorMessage = ko.computed({
        read: function () {
            var html = '';
            if (this.errors().length > 0)
                html += this.errors()[0];
            if (this.errors().length > 1) {
                html += "<ul>"
                for (var idx = 1; idx < this.errors().length; idx++)
                    html += "<li>" + this.errors()[idx] + "</li>";
                html += "</ul>";
            }
            return html;
        },
        write: function (value) {
            this.errors.removeAll();
            this.errors.push(value);
        },
        owner: this
    });


    this.previewHtml = ko.observable();
    this.isPreview = ko.observable(false);

    this.isOdd = ko.observable(true);
    this.isEdit = ko.observable(false);

    this.oldId = ko.observable();
    this.oldTitle = ko.observable();

    this.load = function (item) {
        this.id(item.FileID);
        this.title(item.Title);
        this.type(item.Type);
        this.time(item.FormattedTime);
        for (var idx = 0; idx < item.Categories.length; idx++) {
            var category = item.Categories[idx];
            this.selectedCategories.push(category.CatID);
        }
    }

    this.edit = function () {
        this.isEdit(true);
        this.oldId(this.id());
        this.oldTitle(this.title());
        if (this.categories().length == 0) {
            var url = appPath + 'Category/Get';
            $.get(url, function (data) {
                for (var idx = 0; idx < data.length; idx++) {
                    var category = data[idx];
                    self.categories.push(new option(category.CatID, category.Name));
                }
            });
        }
    }

    this.editLink = ko.computed(function () {
        return appPath + 'Post/Compose/' + this.id();
    }, this);

    this.preview = function () {
        var url = appPath + 'Post/Preview/' + this.id();
        $.get(url, function (data) {
            self.previewHtml(data);
            self.isPreview(true);
        });
    }

    this.closePreview = function () {
        this.isPreview(false);
    }

    this.hasError = ko.computed(function () {
        return this.title.hasError();
    }, this);


    this.setError = function () {
        if (this.hasError()) {
            self.parent.errorMessage("Please correct the following errors:");
            if (this.title.hasError())
                self.parent.errors.push(this.title.validationMessage());
        } else {
            this.clearError();
        }
    }

    this.clearError = function () {
        self.parent.errors.removeAll();
    }


    this.update = function () {
        if (this.hasError()) {
            this.setError();
        } else {
            var url = appPath + 'Post/Update/'
            var input = {
                olid: this.id(),
                FileId: this.id(),
                Title: this.title(),
                Categories: this.selectedCategoriesJson()
            };

            $.post(url, input, function (data) {
                if (data.Result) {
                    // self.parent.redoOdd(); -- not required
                    self.parent.successMessage(data.Message);
                    self.clearError();
                    setInterval(function () { self.parent.successMessage('') }, settings.fadeOutInterval);
                    self.isEdit(false);
                } else {
                    self.parent.errorMessage(data.Message);
                    if (data.Errors) {
                        for (var idx = 0; idx < data.Errors.length; idx++)
                            self.parent.errors.push(data.Errors[idx]);
                    }
                }
            });
        }
    }

    this.remove = function () {
        var url = appPath + 'Post/Delete/' + this.id();
        $.get(url, function (data) {
            if (data.Result) {
                self.parent.successMessage(data.Message);
                setInterval(function () { self.parent.successMessage('') }, settings.fadeOutInterval);
                self.clearError();
                self.parent.remove(self);
                self.parent.redoOdd();
            } else {
                self.parent.errorMessage(data.Message);
            }
        });
    }

    this.unpublish = function () {
        var url = appPath + 'Post/Unpublish/' + this.id() + "?title=" + this.title();
        $.get(url, function (data) {
            if (data.Result) {
                if (data.Data) {
                    self.id(data.Data);
                    self.parent.successMessage(data.Message);
                    setInterval(function () { self.parent.successMessage('') }, settings.fadeOutInterval);
                    self.type(0);
                } else {
                    self.parent.remove(self);
                    self.parent.redoOdd();
                }
                self.clearError();
            } else {
                self.parent.errorMessage(data.Message);
            }
        });
    }

    this.close = function () {
        this.clearError();
        if (this.isEdit()) {
            this.isEdit(false);
            this.id(this.oldId());
            this.title(this.oldTitle());
        }
    }
}

